package com.stt.order.design.service;

import com.stt.order.model.Order;
import com.stt.order.design.factory.PromotionStrategyFactory;
import com.stt.order.design.chain.PromotionHandler;
import com.stt.order.design.strategy.PromotionStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单优惠计算服务
 * 使用策略模式和责任链模式处理订单优惠
 */
@Service
public class PromotionStrategyService {
    
    @Autowired
    private PromotionStrategyFactory strategyFactory;
    
    /**
     * 计算订单优惠金额
     * 1. 解析订单中的促销类型
     * 2. 创建促销策略链
     * 3. 构建责任链
     * 4. 执行优惠计算
     */
    public void calculateDiscount(Order order) {
        // 获取订单可参加的所有促销活动策略集合
        List<PromotionStrategy> strategies = strategyFactory.createPromotionChain(order);
        
        // 构建责任链
        PromotionHandler firstHandler = null;
        PromotionHandler currentHandler = null;
        
        // 遍历所有策略，构建责任链
        for (PromotionStrategy strategy : strategies) {
            PromotionHandler handler = new PromotionHandler(strategy);
            if (firstHandler == null) {
                firstHandler = handler;
            } else {
                currentHandler.setNext(handler);
            }
            currentHandler = handler;
        }
        
        // 执行优惠计算，从责任链的第一个处理器开始
        BigDecimal finalAmount = firstHandler.handle(order, order.getOriginalAmount());
        order.setFinalAmount(finalAmount);
    }
} 